<script setup lang="ts">
import { computed, onBeforeMount, reactive, ref } from 'vue';
import { $t } from '@/locales';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { useAuthStore } from '@/store/modules/auth';
import * as loginService from '@/service/api/login';
import type { UsrPwdParam } from '@/service/api/login';
import { isSuccess } from '@/utils/response';
import { isDevelopment } from '@/utils/profile';

/** 用户名密码+图片验证码登录 */
defineOptions({
  name: 'PwdLogin'
});

const authStore = useAuthStore();
const { formRef, validate } = useNaiveForm();

let defaultParam = {
  username: '',
  password: '',
  captchaId: '',
  captchaVal: ''
};
if (isDevelopment()) {
  defaultParam = {
    username: 'administrator',
    password: 'Aa111111',
    captchaId: '',
    captchaVal: ''
  };
}

const model: UsrPwdParam = reactive(defaultParam);

const captchaImage = ref('');

const rules = computed<Record<keyof UsrPwdParam, App.Global.FormRule[]>>(() => {
  const { formRules } = useFormRules(); // inside computed to make locale reactive

  return {
    username: formRules.userName,
    password: formRules.pwd,
    captchaId: formRules.captchaId,
    captchaVal: formRules.captchaVal
  };
});

async function handleSubmit() {
  await validate();
  await authStore.loginByUsrPwd(model);
}

async function getCaptcha() {
  const response = await loginService.getCaptcha('Login');
  if (isSuccess(response)) {
    const captcha = response.data;
    model.captchaId = captcha.captchaId;
    model.captchaVal = captcha.captchaVal;
    captchaImage.value = `data:image/jpeg;charset=utf-8;base64,${captcha.image}`;
  }
}

onBeforeMount(() => {
  getCaptcha();
});
</script>

<template>
  <NForm ref="formRef" :model="model" :rules="rules" size="large" :show-label="false">
    <NFormItem path="userName">
      <NInput v-model:value="model.username" :placeholder="$t('page.login.common.userNamePlaceholder')" />
    </NFormItem>
    <NFormItem path="password">
      <NInput
        v-model:value="model.password"
        type="password"
        :placeholder="$t('page.login.common.passwordPlaceholder')"
      />
    </NFormItem>
    <NFormItem>
      <NRow justify-content="space-around" align-items="center">
        <img class="captcha-img" :src="captchaImage" @click="getCaptcha" />
        <NInput v-model:value="model.captchaVal" class="captcha-val" type="text" autosize placeholder="验证码" />
      </NRow>
    </NFormItem>
    <NSpace vertical :size="24">
      <div class="flex-y-center justify-between">
        <NCheckbox>{{ $t('page.login.pwdLogin.rememberMe') }}</NCheckbox>
      </div>
      <NButton type="primary" size="large" block round :loading="authStore.loginLoading" @click="handleSubmit">
        {{ $t('common.confirm') }}
      </NButton>
    </NSpace>
  </NForm>
</template>

<style scoped>
.captcha-img {
  width: 180px;
  height: 60px;
  background-color: white;
}
.captcha-val {
  min-width: 100px;
}
</style>
